package niodemo.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import niodemo.domin.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: jimao.zou
 * @Date: 8/14/2018 11:36 AM
 */
public class Client {
    private final static Integer BUFFERSIZE = 1024;
    private Selector selector;
    private SocketChannel clientChannel;
    private ObjectMapper objectMapper = new ObjectMapper();


    private void initNetWork() {
        try {
            selector = Selector.open();
            clientChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9000));
            //设置客户端为非阻塞模式
            clientChannel.configureBlocking(false);
            clientChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void exchangeMessage() {
        try {
            Message message = new Message() {{
                setContent("开始疯狂地轰炸吧");
            }};
            byte[] sendMessage = objectMapper.writeValueAsBytes(message);

            clientChannel.write(ByteBuffer.wrap(sendMessage));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    class ListenerThread implements Runnable {
        private ByteBuffer byteBuffer;
        ByteArrayOutputStream acceptedStream;

        public ListenerThread() {
            this.byteBuffer = ByteBuffer.allocate(BUFFERSIZE);
            acceptedStream = new ByteArrayOutputStream();
        }

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    selector.select();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    for (Iterator<SelectionKey> keys = selectionKeys.iterator(); keys.hasNext(); ) {
                        SelectionKey key = keys.next();
                        keys.remove();
                        if (key.isReadable()) {
                            int size;
                            while ((size = clientChannel.read(byteBuffer)) > 0) {
                                byteBuffer.flip();
                                acceptedStream.write(byteBuffer.array(), 0, size);
                                byteBuffer.clear();
                            }
                            //序列化信息
                            Message receptedMessage =
                                    objectMapper.readValue(acceptedStream.toByteArray(), Message.class);
                            acceptedStream.close();
                            System.out.println("劳资客户端收到信息啦，比比锤子：" + receptedMessage);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void launch() {
        new Thread(new ListenerThread()).start();
    }

    public static void main(String[] args) {
        System.out.println("Initialing...");
        Client client = new Client();
        client.initNetWork();
        client.exchangeMessage();
        client.launch();

//        client.launch();
    }
}